package models

import (
	"errors"
	"math/rand"
	"reflect"
	"strings"

	"github.com/beego/beego/v2/client/orm"
)

type Anchor_info struct {
	AnchorId      int64 `orm:"auto"`
	SubRegionId   int
	Status        int
	DisableStatus int8
	LiveModel     int
	ActiveTime    int64
	Nick          string
	HeadImg       string
	Age           int
	Gender        int
	FastOrder     int
}

func init() {
	orm.RegisterModel(new(Anchor_info))
}

// AddAnchor_info insert a new Anchor_info into database and returns
// last inserted Id on success.
func AddAnchor_info(m *Anchor_info) (AnchorId int64, err error) {
	o := orm.NewOrm()
	AnchorId, err = o.Insert(m)
	return
}

// GetAnchor_infoById retrieves Anchor_info by AnchorId. Returns error if
// Id doesn't exist
func GetAnchor_infoByAnchorId(anchorId int64) (v *Anchor_info, err error) {
	o := orm.NewOrm()
	v = &Anchor_info{}
	if err = o.QueryTable(new(Anchor_info)).Filter("anchor_id", anchorId).RelatedSel().One(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetExistAnchor_infoByAnchorId(anchorId int64) (exist bool) {
	o := orm.NewOrm()
	exist = o.QueryTable(new(Anchor_info)).Filter("anchor_id", anchorId).RelatedSel().Exist()
	return
}

// GetAllAnchor_info retrieves all Anchor_info matches certain condition. Returns empty list if
// no records exist
func GetAllAnchor_info(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Anchor_info))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []Anchor_info
	qs = qs.OrderBy(sortFields...).RelatedSel()
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// 获取所有在线可接单主播列表
func GetOnlineTakingOrderAnchors() (v []Anchor_info, err error) {
	o := orm.NewOrm()

	// 查询符合条件的主播数量，排除黑名单中的主播
	sql := `SELECT anchor_id,sub_region_id,status FROM anchor_info WHERE status IN (2, 3) AND disable_status = 0 AND live_model != 2 LIMIT 10000 `
	_, err = o.Raw(sql).QueryRows(&v)
	if err != nil {
		return nil, err
	}

	return
}

// UpdateAnchor_info updates Anchor_info by AnchorId and returns error if
// the record to be updated doesn't exist
func UpdateAnchor_infoByAnchorId(m *Anchor_info) (err error) {
	o := orm.NewOrm()
	v := Anchor_info{AnchorId: m.AnchorId}
	// ascertain anchor_id exists in the database
	if err = o.Read(&v); err == nil {
		//var num int64
		if _, err = o.Update(m); err != nil {
			return
		}
	}
	return
}

func UpdateAnchor_infoByAnchorIdAndFields(m *Anchor_info, fields []string) (err error) {
	o := orm.NewOrm()
	v := Anchor_info{AnchorId: m.AnchorId}
	// ascertain anchor_id exists in the database
	if err = o.Read(&v); err == nil {
		//var num int64
		if _, err = o.Update(m, fields...); err != nil {
			return
		}
	}
	return
}

func TxUpdateAnchor_infoByAnchorIdAndFields(tx orm.TxOrmer, m *Anchor_info, fields []string) (err error) {
	//o := orm.NewOrm()
	v := Anchor_info{AnchorId: m.AnchorId}
	// ascertain anchor_id exists in the database
	if err = tx.Read(&v); err == nil {
		//var num int64
		if _, err = tx.Update(m, fields...); err != nil {
			return
		}
	}
	return
}

// DeleteAnchor_info deletes Anchor_info by AnchorId and returns error if
// the record to be deleted doesn't exist
func DeleteAnchor_info(anchorId int64) (err error) {
	o := orm.NewOrm()
	v := Anchor_info{AnchorId: anchorId}
	// ascertain AnchorId exists in the database
	if err = o.Read(&v); err == nil {
		//var num int64
		if _, err = o.Delete(&Anchor_info{AnchorId: anchorId}); err != nil {
			return
		}
	}
	return
}

// 随机中在线、空闲状态主播中选取一个主播
//func GetRandomAnchorId() (userId int64, err error) {
//	o := orm.NewOrm()
//	v := &Anchor_info{}
//	cond := orm.NewCondition()
//	cond.And("status__in", []int{constants.ANCHOR_ONLINEIDLE, constants.ANCHOR_ONLINETAKINGORDERS})
//	cond.And("anchor_id__not_in", "select anchor_id from anchor_info where viewer_id = userId status =1")
//	count, err := o.QueryTable(new(Anchor_info)).SetCond(cond).RelatedSel().Count()
//	if err != nil {
//		return nil, err
//	}
//	if count == 0 {
//		return nil, errors.New("没有可接单主播")
//	}
//
//	randomIndex := rand.Intn(int(count))
//	err = o.QueryTable(new(Anchor_info)).SetCond(cond).RelatedSel().Limit(1).Offset(randomIndex).One(v)
//	if err != nil {
//		return nil, err
//	}
//	return v, err
//}

func GetRandomAnchorId(userId int64) (v *Anchor_info, err error) {
	o := orm.NewOrm()
	var count int64

	// 查询符合条件的主播数量，排除黑名单中的主播
	sql := `SELECT COUNT(*) FROM anchor_info 
			WHERE status IN (2, 3) 
			AND anchor_id NOT IN (
				SELECT operator_id FROM black_list 
				WHERE target_id = ? AND status = 1
			) AND anchor_id NOT IN (
				SELECT target_id FROM black_list 
				WHERE operator_id = ? AND status = 1
			)`
	err = o.Raw(sql, userId, userId).QueryRow(&count)
	if err != nil {
		return nil, err
	}

	if count == 0 {
		return nil, errors.New("没有可接单主播")
	}

	// 随机选择一个主播索引
	randomIndex := rand.Intn(int(count))

	// 查询随机主播的信息
	sql = `SELECT * FROM anchor_info
			WHERE status IN (2, 3)
			AND anchor_id NOT IN (
				SELECT operator_id FROM black_list
				WHERE target_id = ? AND status = 1
			) AND anchor_id NOT IN (
				SELECT target_id FROM black_list
				WHERE operator_id = ? AND status = 1
			)
		   LIMIT 1 OFFSET ?`
	v = &Anchor_info{}
	err = o.Raw(sql, userId, userId, randomIndex).QueryRow(v)
	if err != nil {
		return nil, errors.New("无法检索随机主播信息")
	}

	return v, nil
}

func GetOnlineTakingOrderAnchorIds(userId int64) (list []int64, err error) {
	o := orm.NewOrm()
	v := []Anchor_info{}
	list = make([]int64, 0)

	// 查询符合条件的主播数量，排除黑名单中的主播
	sql := `SELECT anchor_id FROM anchor_info 
			WHERE status IN (2, 3) 
			AND anchor_id NOT IN (
				SELECT operator_id FROM black_list 
				WHERE target_id = ? AND status = 1
			) AND anchor_id NOT IN (
				SELECT target_id FROM black_list 
				WHERE operator_id = ? AND status = 1
			)
			LIMIT 100 `
	_, err = o.Raw(sql, userId, userId).QueryRows(&v)
	if err != nil {
		return nil, err
	}

	if len(v) == 0 {
		return nil, errors.New("没有可接单主播")
	}

	for _, info := range v {
		list = append(list, info.AnchorId)
	}

	return list, nil
}
